package com.ruoyi.ldzlsc.service.Impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ldzlsc.domain.ScScheduling;
import com.ruoyi.ldzlsc.domain.ScWorkOrder;
import com.ruoyi.ldzlsc.domain.ScWorkOrderTask;
import com.ruoyi.ldzlsc.domain.vo.ScProductionPlanVo;
import com.ruoyi.ldzlsc.mapper.ScProductionOrderMapper;
import com.ruoyi.ldzlsc.mapper.ScProductionPlanMapper;
import com.ruoyi.ldzlsc.mapper.ScSchedulingMapper;
import com.ruoyi.ldzlsc.mapper.ScWorkOrderMapper;
import com.ruoyi.ldzlsc.mapper.ScWorkOrderTaskMapper;
import com.ruoyi.ldzlsc.service.IScWorkOrderTaskService;
import com.ruoyi.system.api.BasicService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.ruoyi.ldzlsc.domain.vo.WorkOrderVO;
import com.ruoyi.ldzlsc.domain.vo.ScTaskVo;
import com.ruoyi.ldzlsc.domain.vo.*;

import java.math.BigDecimal;

/**
 * 工单任务Service业务层处理
 *
 * @author ldl
 * @date 2023-04-05
 */
@Service
public class ScWorkOrderTaskServiceImpl implements IScWorkOrderTaskService {

    @Autowired
    private ScWorkOrderTaskMapper scWorkOrderTaskMapper;
    
    @Autowired
    private ScWorkOrderMapper scWorkOrderMapper;
    
    @Autowired
    private ScProductionPlanMapper scProductionPlanMapper;
    
    @Autowired
    private ScProductionOrderMapper scProductionOrderMapper;

    @Autowired
    private BasicService basicService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RemoteDeptService remoteDeptService;

    @Autowired
    private ScSchedulingMapper scSchedulingMapper;

    @Override
    public List<ScWorkOrderTask> selectScWorkOrderTaskList(ScWorkOrderTask scWorkOrderTask) {
        return scWorkOrderTaskMapper.selectScWorkOrderTaskList(scWorkOrderTask);
    }

    @Override
    public List<ScTaskVo> selectReportableTaskList(ScTaskVo query) {
        return scWorkOrderTaskMapper.selectReportableTaskList(query);
    }

    @Override
    @Transactional
    public void saveSchedule(Long workOrderId, List<ScWorkOrderTask> tasks) {
        String username = SecurityUtils.getUsername();

        // 1. 根据 workOrderId 删除所有已存在的 WorkOrderTask 记录和排产计划记录
        scWorkOrderTaskMapper.deleteScWorkOrderTaskByWorkOrderId(workOrderId);
        scSchedulingMapper.deleteScSchedulingByWorkOrderId(workOrderId);

        // 2. 批量插入这个新的任务列表
        if (tasks != null && !tasks.isEmpty()) {
            for (ScWorkOrderTask task : tasks) {
                task.setWorkOrderId(workOrderId);
                task.setTaskCode(generateCode(18L));
                task.setStatus("0"); // 设置默认状态为'0' (未开始)
                task.setCreateBy(username);
            }
            scWorkOrderTaskMapper.batchInsertWorkOrderTasks(tasks);

            // 3. 创建对应的排产计划记录
            List<ScScheduling> schedulingList = new ArrayList<>();
            for (ScWorkOrderTask task : tasks) {
                ScScheduling scheduling = new ScScheduling();
                scheduling.setWorkOrderId(workOrderId);
                scheduling.setProcessId(task.getProcessId());
                scheduling.setResourceType("STATION"); // 资源类型：工位
                scheduling.setResourceId(task.getStationId()); // 资源ID：工位ID
                scheduling.setScheduleStart(task.getStartTime());
                scheduling.setScheduleEnd(task.getEndTime());
                scheduling.setStatus("0"); // 状态：未开始
                scheduling.setCreateBy(username);
                schedulingList.add(scheduling);
            }

            if (!schedulingList.isEmpty()) {
                scSchedulingMapper.batchInsertScScheduling(schedulingList);
            }
        }

        // 4. 更新工单状态为"1-未开始"（已排产）
        updateWorkOrderStatusAfterSchedule(workOrderId);
    }

    /**
     * 排产完成后更新工单状态
     *
     * @param workOrderId 工单ID
     */
    private void updateWorkOrderStatusAfterSchedule(Long workOrderId) {
        // 获取工单当前状态
        WorkOrderVO workOrderVO = scWorkOrderMapper.selectWorkOrderById(workOrderId);
        if (workOrderVO == null) {
            System.err.println("工单不存在，ID: " + workOrderId);
            return;
        }

        // 只有状态为"0-待排产"的工单才需要更新状态
        if ("0".equals(workOrderVO.getStatus())) {
            ScWorkOrder updateOrder = new ScWorkOrder();
            updateOrder.setWorkOrderId(workOrderId);
            updateOrder.setStatus("1"); // 1-未开始（已排产）
            updateOrder.setUpdateBy(SecurityUtils.getUsername());
            updateOrder.setUpdateTime(DateUtils.getNowDate());

            int rows = scWorkOrderMapper.updateWorkOrder(updateOrder);
            if (rows > 0) {
                System.out.println("排产完成，工单状态更新成功，工单ID: " + workOrderId + ", 新状态: 1-未开始");
            } else {
                System.err.println("排产完成，工单状态更新失败，工单ID: " + workOrderId);
            }
        } else {
            System.out.println("工单状态不是待排产状态，无需更新，当前状态: " + workOrderVO.getStatus() + ", 工单ID: " + workOrderId);
        }
    }
    
    @Override
    @Transactional
    public int startTask(Long workOrderTaskId) {
        // 1. 获取工序任务详情
        ScWorkOrderTask task = scWorkOrderTaskMapper.selectScWorkOrderTaskByWorkOrderTaskId(workOrderTaskId);
        if (task == null) {
            throw new ServiceException("工序任务不存在");
        }
        
        System.out.println("开始处理工序任务开工，ID: " + workOrderTaskId + ", 当前状态: " + task.getStatus());
        
        // 判断当前状态是否允许开工
        if (!"0".equals(task.getStatus()) && !"1".equals(task.getStatus())) {
            throw new ServiceException("当前工序任务状态不是待开工状态，无法开工");
        }
        
        // 移除设置初始进度的逻辑，开工时只更新状态和时间，不修改数量
        // 这样可以避免报工时数量限制的问题
        
        // 更新工序任务状态
        Date now = DateUtils.getNowDate();
        ScWorkOrderTask updateTask = new ScWorkOrderTask();
        updateTask.setWorkOrderTaskId(workOrderTaskId);
        updateTask.setStatus("2"); // 2-进行中（已开工但未报工）
        // 移除：updateTask.setCompletedQty(initialProgress); // 不再设置初始进度
        updateTask.setStartTime(now); // 记录实际开始时间
        updateTask.setUpdateBy(SecurityUtils.getUsername());
        updateTask.setUpdateTime(now);
        int rows = scWorkOrderTaskMapper.updateScWorkOrderTask(updateTask);

        if (rows > 0) {
            System.out.println("工序任务状态更新成功，ID: " + workOrderTaskId + ", 新状态: 2-进行中，不设置初始进度");
            // 检查并更新上级工单状态
            updateWorkOrderStatus(task.getWorkOrderId(), now);
        } else {
            System.err.println("工序任务状态更新失败，ID: " + workOrderTaskId);
        }
        return rows;
    }

    @Override
    @Transactional
    public int completeTask(Long workOrderTaskId) {
        // 1. 获取工序任务详情
        ScWorkOrderTask task = scWorkOrderTaskMapper.selectScWorkOrderTaskByWorkOrderTaskId(workOrderTaskId);
        if (task == null) {
            throw new ServiceException("工序任务不存在");
        }

        System.out.println("开始处理工序任务完成，ID: " + workOrderTaskId + ", 当前状态: " + task.getStatus());

        // 判断当前状态是否允许完成
        if (!"1".equals(task.getStatus()) && !"2".equals(task.getStatus())) {
            throw new ServiceException("当前工序任务状态不允许完成操作");
        }

        // 2. 更新工序任务状态
        Date now = DateUtils.getNowDate();
        ScWorkOrderTask updateTask = new ScWorkOrderTask();
        updateTask.setWorkOrderTaskId(workOrderTaskId);
        updateTask.setStatus("3"); // 3-已完成
        updateTask.setActualEndTime(now); // 记录实际结束时间
        updateTask.setUpdateBy(SecurityUtils.getUsername());
        updateTask.setUpdateTime(now);
        int rows = scWorkOrderTaskMapper.updateScWorkOrderTask(updateTask);

        if (rows > 0) {
            System.out.println("工序任务状态更新成功，ID: " + workOrderTaskId + ", 新状态: 3-已完成");
            // 3. 检查并更新上级工单状态
            updateWorkOrderStatus(task.getWorkOrderId(), now);
        } else {
            System.err.println("工序任务状态更新失败，ID: " + workOrderTaskId);
        }
        return rows;
    }

    @Override
    @Transactional
    public int pauseTask(Long workOrderTaskId) {
        // 1. 获取工序任务详情
        ScWorkOrderTask task = scWorkOrderTaskMapper.selectScWorkOrderTaskByWorkOrderTaskId(workOrderTaskId);
        if (task == null) {
            throw new ServiceException("工序任务不存在");
        }

        System.out.println("开始处理工序任务暂停，ID: " + workOrderTaskId + ", 当前状态: " + task.getStatus());

        // 判断当前状态是否允许暂停
        if (!"1".equals(task.getStatus()) && !"2".equals(task.getStatus())) {
            throw new ServiceException("当前工序任务状态不允许暂停操作");
        }

        // 2. 更新工序任务状态
        Date now = DateUtils.getNowDate();
        ScWorkOrderTask updateTask = new ScWorkOrderTask();
        updateTask.setWorkOrderTaskId(workOrderTaskId);
        updateTask.setStatus("4"); // 4-已暂停
        updateTask.setUpdateBy(SecurityUtils.getUsername());
        updateTask.setUpdateTime(now);
        int rows = scWorkOrderTaskMapper.updateScWorkOrderTask(updateTask);

        if (rows > 0) {
            System.out.println("工序任务状态更新成功，ID: " + workOrderTaskId + ", 新状态: 4-已暂停");
        } else {
            System.err.println("工序任务状态更新失败，ID: " + workOrderTaskId);
        }
        return rows;
    }

    @Override
    @Transactional
    public int restartTask(Long workOrderTaskId) {
        // 1. 获取工序任务详情
        ScWorkOrderTask task = scWorkOrderTaskMapper.selectScWorkOrderTaskByWorkOrderTaskId(workOrderTaskId);
        if (task == null) {
            throw new ServiceException("工序任务不存在");
        }

        System.out.println("开始处理工序任务重启，ID: " + workOrderTaskId + ", 当前状态: " + task.getStatus());

        // 判断当前状态是否允许重启
        if (!"3".equals(task.getStatus()) && !"4".equals(task.getStatus()) && !"5".equals(task.getStatus())) {
            throw new ServiceException("当前工序任务状态不允许重启操作");
        }

        // 2. 更新工序任务状态
        Date now = DateUtils.getNowDate();
        ScWorkOrderTask updateTask = new ScWorkOrderTask();
        updateTask.setWorkOrderTaskId(workOrderTaskId);
        updateTask.setStatus("1"); // 1-已派工
        updateTask.setActualEndTime(null); // 清空实际结束时间
        updateTask.setUpdateBy(SecurityUtils.getUsername());
        updateTask.setUpdateTime(now);
        int rows = scWorkOrderTaskMapper.updateScWorkOrderTask(updateTask);

        if (rows > 0) {
            System.out.println("工序任务状态更新成功，ID: " + workOrderTaskId + ", 新状态: 1-已派工");
        } else {
            System.err.println("工序任务状态更新失败，ID: " + workOrderTaskId);
        }
        return rows;
    }

    /**
     * 更新工单状态
     * 
     * @param workOrderId 工单ID
     * @param startTime 实际开始时间
     */
    private void updateWorkOrderStatus(Long workOrderId, Date startTime) {
        // 通过WorkOrderId获取工单详情
        WorkOrderVO workOrderVO = scWorkOrderMapper.selectWorkOrderById(workOrderId);
        if (workOrderVO == null) {
            return;
        }
        
        // 判断工单状态是否为"0-未开始"或"1-待开工"，如果是则更新状态
        if ("0".equals(workOrderVO.getStatus()) || "1".equals(workOrderVO.getStatus())) {
            ScWorkOrder updateOrder = new ScWorkOrder();
            updateOrder.setWorkOrderId(workOrderId);
            updateOrder.setStatus("2"); // 2-进行中
            updateOrder.setActualStartTime(startTime);
            updateOrder.setUpdateBy(SecurityUtils.getUsername());
            updateOrder.setUpdateTime(DateUtils.getNowDate());

            int rows = scWorkOrderMapper.updateWorkOrder(updateOrder);
            if (rows > 0) {
                System.out.println("工单状态更新成功，工单ID: " + workOrderId + ", 新状态: 2-进行中");
                
                // 4. 检查并更新上级生产计划状态
                Long productionPlanId = null;
                try {
                    // 从WorkOrderVO中获取planCode，然后查询对应的生产计划ID
                    String planCode = workOrderVO.getPlanCode();
                    if (planCode != null && !planCode.isEmpty()) {
                        ScProductionPlanVo plan = scProductionPlanMapper.selectScProductionPlanByPlanCode(planCode);
                        if (plan != null) {
                            productionPlanId = plan.getProductionPlanId();
                        }
                    }
                } catch (Exception e) {
                    // 记录日志但不中断流程
                    System.err.println("获取生产计划ID失败: " + e.getMessage());
                }
                
                if (productionPlanId != null) {
                    updateProductionPlanStatus(productionPlanId);
                }
            } else {
                System.err.println("工单状态更新失败，工单ID: " + workOrderId);
            }
        } else {
            System.out.println("工单状态不需要更新，当前状态: " + workOrderVO.getStatus() + ", 工单ID: " + workOrderId);
        }
    }
    
    /**
     * 更新生产计划状态
     * 
     * @param productionPlanId 生产计划ID
     */
    private void updateProductionPlanStatus(Long productionPlanId) {
        if (productionPlanId == null) {
            return;
        }
        
        // 获取生产计划信息
        ScProductionPlanVo productionPlan = scProductionPlanMapper.selectScProductionPlanById(productionPlanId);
        if (productionPlan == null) {
            System.err.println("未找到生产计划，ID: " + productionPlanId);
            return;
        }
        
        System.out.println("检查生产计划状态，ID: " + productionPlanId + ", 当前状态: " + productionPlan.getStatus());
        
        // 判断生产计划状态是否为"0-未开始"、"1-已分解"或"2-待执行"
        if ("0".equals(productionPlan.getStatus()) || "1".equals(productionPlan.getStatus()) || "2".equals(productionPlan.getStatus())) {
            // 更新生产计划状态为"3-执行中"
            int rows = scProductionPlanMapper.updateScProductionPlanStatus(productionPlan.getPlanCode(), "3");
            if (rows > 0) {
                System.out.println("生产计划状态更新成功，ID: " + productionPlanId + ", 新状态: 3-执行中");
                // 5. 检查并更新顶层生产订单状态
                updateProductionOrderStatus(productionPlan.getProductionOrderId());
            } else {
                System.err.println("生产计划状态更新失败，ID: " + productionPlanId);
            }
        } else {
            System.out.println("生产计划状态不需要更新，当前状态: " + productionPlan.getStatus() + ", ID: " + productionPlanId);
        }
    }
    
    /**
     * 更新生产订单状态
     * 
     * @param productionOrderId 生产订单ID
     */
    private void updateProductionOrderStatus(Long productionOrderId) {
        if (productionOrderId == null) {
            return;
        }
        
        // 获取生产订单信息
        String status = scProductionOrderMapper.selectProductionOrderStatusById(productionOrderId);
        if (status == null) {
            System.err.println("未找到生产订单状态，ID: " + productionOrderId);
            return;
        }
        
        System.out.println("检查生产订单状态，ID: " + productionOrderId + ", 当前状态: " + status);
        
        // 判断生产订单状态是否为"0-未开始"、"1-已下达"或"2-待生产"
        if ("0".equals(status) || "1".equals(status) || "2".equals(status)) {
            // 更新生产订单状态为"3-生产中"
            int rows = scProductionOrderMapper.updateProductionOrderStatus(productionOrderId, "3");
            if (rows > 0) {
                System.out.println("生产订单状态更新成功，ID: " + productionOrderId + ", 新状态: 3-生产中");
            } else {
                System.err.println("生产订单状态更新失败，ID: " + productionOrderId);
            }
        } else {
            System.out.println("生产订单状态不需要更新，当前状态: " + status + ", ID: " + productionOrderId);
        }
    }

    /**
     * 远程调用基础服务生成编码，并健壮地处理返回结果。
     * @param type 编码类型
     * @return 生成的编码字符串
     */
    private String generateCode(Long type) {
        // 调用远程服务（消费模式，确保每次调用都会递增流水号）
        AjaxResult codeResult = basicService.automaticallyNumbersConsume(type);

        // 确保远程调用返回了结果对象
        if (codeResult == null) {
            throw new ServiceException(String.format("远程获取编码调用失败，返回结果为空，类型: %d", type));
        }

        // 根据该接口的特殊设计，编码直接存放在msg字段
        Object msg = codeResult.get(AjaxResult.MSG_TAG);
        Object code=codeResult.get(AjaxResult.CODE_TAG);
        System.out.println("编码是："+code);
        // 确保编码内容不为空
        if (msg == null || msg.toString().isEmpty()) {
            throw new ServiceException(String.format("远程获取编码成功，但返回的编码为空，类型: %d, 返回信息: %s", type, msg));
        }

        // 从AjaxResult中正确取出msg部分作为编码
        return msg.toString();
    }

    @Override
    public WorkOrderTaskDetailVO getWorkOrderTaskDetail(Long workOrderTaskId) {
        // 直接获取工序任务详细信息（包含所有关联数据）
        WorkOrderTaskDetailVO detailVO = scWorkOrderTaskMapper.selectWorkOrderTaskDetailById(workOrderTaskId);
        if (detailVO == null) {
            throw new ServiceException("工序任务不存在");
        }

        // 获取派工信息并从中提取质检信息
        WorkOrderTaskDetailVO.DispatchInfo dispatchInfo = getTaskDispatch(workOrderTaskId);
        if (dispatchInfo != null) {
            detailVO.setDispatchInfo(dispatchInfo);

            // 从派工信息中提取质检信息
            WorkOrderTaskDetailVO.QcInfo qcInfo = new WorkOrderTaskDetailVO.QcInfo();

            // 获取质检部门名称
            if (dispatchInfo.getQcDeptId() != null) {
                try {
                    R<SysDept> deptResult = remoteDeptService.getDeptById(dispatchInfo.getQcDeptId(), SecurityConstants.INNER);
                    if (deptResult != null && deptResult.getData() != null) {
                        qcInfo.setQcDepartment(deptResult.getData().getDeptName());
                    }
                } catch (Exception e) {
                    qcInfo.setQcDepartment("暂无");
                }
            } else {
                qcInfo.setQcDepartment("暂无");
            }

            // 获取质检人员姓名
            if (dispatchInfo.getQcPersonId() != null) {
                try {
                    R<SysUser> userResult = remoteUserService.getUserById(dispatchInfo.getQcPersonId(), SecurityConstants.INNER);
                    if (userResult != null && userResult.getData() != null) {
                        SysUser user = userResult.getData();
                        qcInfo.setQcInspector(user.getNickName() != null ? user.getNickName() : user.getUserName());
                    }
                } catch (Exception e) {
                    qcInfo.setQcInspector("暂无");
                }
            } else {
                qcInfo.setQcInspector("暂无");
            }

            // 设置质检备注（可以从派工备注中获取，或者设置为空）
            qcInfo.setQcRemark(dispatchInfo.getDispatchRemark());

            detailVO.setQcInfo(qcInfo);
        } else {
            // 如果没有派工信息，设置默认的质检信息
            WorkOrderTaskDetailVO.QcInfo qcInfo = new WorkOrderTaskDetailVO.QcInfo();
            qcInfo.setQcDepartment("暂无");
            qcInfo.setQcInspector("暂无");
            qcInfo.setQcRemark("");
            detailVO.setQcInfo(qcInfo);
        }

        return detailVO;
    }

    @Override
    public List<TaskMaterialVO> getTaskMaterials(Long workOrderTaskId) {
        return scWorkOrderTaskMapper.selectTaskMaterialsByTaskId(workOrderTaskId);
    }

    @Override
    public List<TaskReportVO> getTaskReports(Long workOrderTaskId) {
        return scWorkOrderTaskMapper.selectTaskReportsByTaskId(workOrderTaskId);
    }

    @Override
    public List<TaskReturnVO> getTaskReturns(Long workOrderTaskId) {
        return scWorkOrderTaskMapper.selectTaskReturnsByTaskId(workOrderTaskId);
    }

    @Override
    public List<TaskProgressVO> getTaskProgress(Long workOrderTaskId) {
        return scWorkOrderTaskMapper.selectTaskProgressByTaskId(workOrderTaskId);
    }

    @Override
    public WorkOrderTaskDetailVO.DispatchInfo getTaskDispatch(Long workOrderTaskId) {
        WorkOrderTaskDetailVO.DispatchInfo dispatchInfo = scWorkOrderTaskMapper.selectTaskDispatchByTaskId(workOrderTaskId);
        if (dispatchInfo == null) {
            return null;
        }

        // 获取派工人员真实姓名
        if (dispatchInfo.getDispatcher() != null) {
            try {
                R<LoginUser> userResult = remoteUserService.getUserInfo(dispatchInfo.getDispatcher(), SecurityConstants.INNER);
                if (userResult != null && userResult.getData() != null) {
                    SysUser user = userResult.getData().getSysUser();
                    if (user != null) {
                        dispatchInfo.setDispatcher(user.getNickName() != null ? user.getNickName() : user.getUserName());
                    }
                }
            } catch (Exception e) {
                // 远程调用失败时保持原值
            }
        }

        // 获取班组真实名称
        if (dispatchInfo.getTeamId() != null) {
            try {
                R<SysDept> deptResult = remoteDeptService.getDeptById(dispatchInfo.getTeamId(), SecurityConstants.INNER);
                if (deptResult != null && deptResult.getData() != null) {
                    dispatchInfo.setTeamName(deptResult.getData().getDeptName());
                }
            } catch (Exception e) {
                // 远程调用失败时设置默认值
                dispatchInfo.setTeamName("暂无");
            }
        } else {
            dispatchInfo.setTeamName("暂无");
        }

        // 获取负责人真实姓名
        if (dispatchInfo.getLeaderId() != null) {
            try {
                R<SysUser> userResult = remoteUserService.getUserById(dispatchInfo.getLeaderId(), SecurityConstants.INNER);
                if (userResult != null && userResult.getData() != null) {
                    SysUser user = userResult.getData();
                    dispatchInfo.setSupervisor(user.getNickName() != null ? user.getNickName() : user.getUserName());
                }
            } catch (Exception e) {
                // 远程调用失败时设置默认值
                dispatchInfo.setSupervisor("暂无");
            }
        } else {
            dispatchInfo.setSupervisor("暂无");
        }

        // 处理成员ID列表，获取成员真实姓名
        if (dispatchInfo.getMemberIds() != null && !dispatchInfo.getMemberIds().isEmpty()) {
            try {
                String[] memberIdArray = dispatchInfo.getMemberIds().split(",");
                StringBuilder memberNames = new StringBuilder();
                for (String memberId : memberIdArray) {
                    if (memberId.trim().isEmpty()) continue;
                    try {
                        Long userId = Long.parseLong(memberId.trim());
                        R<SysUser> userResult = remoteUserService.getUserById(userId, SecurityConstants.INNER);
                        if (userResult != null && userResult.getData() != null) {
                            SysUser user = userResult.getData();
                            String userName = user.getNickName() != null ? user.getNickName() : user.getUserName();
                            if (memberNames.length() > 0) {
                                memberNames.append(", ");
                            }
                            memberNames.append(userName);
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效的ID
                    } catch (Exception e) {
                        // 远程调用失败时忽略该成员
                    }
                }
                dispatchInfo.setMembers(memberNames.length() > 0 ? memberNames.toString() : "暂无成员");
            } catch (Exception e) {
                dispatchInfo.setMembers("暂无成员");
            }
        } else {
            dispatchInfo.setMembers("暂无成员");
        }

        return dispatchInfo;
    }


}